import folium
from folium.plugins import MarkerCluster
import os
import codecs

# 创建保存地图的目录
os.makedirs('/home/ubuntu/changsha-travel-guide/public/maps', exist_ok=True)

# 长沙市中心坐标
changsha_center = [28.2282, 112.9388]

# 定义图标颜色
colors = {
    'attraction': 'red',
    'food': 'orange',
    'shopping': 'blue',
    'hotel': 'green',
    'transport': 'purple'
}

# 定义自定义图标
icon_dict = {
    'attraction': 'camera',
    'food': 'cutlery',
    'shopping': 'shopping-cart',
    'hotel': 'home',
    'transport': 'subway'
}

# 第一天景点和美食
day1_locations = [
    {'name': '长沙站', 'location': [28.1917, 113.0119], 'type': 'transport', 'description': '抵达长沙站'},
    {'name': '培元桥附近酒店', 'location': [28.1962, 112.9783], 'type': 'hotel', 'description': '入住酒店休息'},
    {'name': '五一广场', 'location': [28.1962, 112.9783], 'type': 'attraction', 'description': '欣赏广场建筑和城市风貌，体验"纽约长沙街"的繁华氛围'},
    {'name': '黄兴路步行街', 'location': [28.1929, 112.9775], 'type': 'shopping', 'description': '感受"三湘商业第一街"的繁华，购物、拍照打卡'},
    {'name': '太平老街', 'location': [28.1896, 112.9775], 'type': 'attraction', 'description': '欣赏保留原有街巷格局最完整的一条街，了解贾谊故居文化'},
    {'name': '坡子街', 'location': [28.1881, 112.9775], 'type': 'food', 'description': '体验1200多年历史的民俗名食街，品尝糖油粑粑、姊妹团子等不辣小吃'},
    {'name': '火宫殿', 'location': [28.1881, 112.9775], 'type': 'food', 'description': '品尝臭豆腐（可要求微辣）、糖油粑粑（不辣）等特色美食'},
    {'name': 'IFS国金中心', 'location': [28.1962, 112.9783], 'type': 'shopping', 'description': '参观七楼的Kaws网红打卡点，购物休闲'},
    {'name': '长沙摩天轮', 'location': [28.1962, 112.9783], 'type': 'attraction', 'description': '乘坐摩天轮俯瞰长沙夜景，拍摄夜景照片'}
]

# 第二天景点和美食
day2_locations = [
    {'name': '培元桥附近酒店', 'location': [28.1962, 112.9783], 'type': 'hotel', 'description': '酒店早餐'},
    {'name': '岳麓山', 'location': [28.1792, 112.9311], 'type': 'attraction', 'description': '游览岳麓山，体验融儒、佛、道为一体的文化名山'},
    {'name': '岳麓书院', 'location': [28.1803, 112.9344], 'type': 'attraction', 'description': '参观中国四大书院之一的岳麓书院'},
    {'name': '爱晚亭', 'location': [28.1803, 112.9344], 'type': 'attraction', 'description': '欣赏爱晚亭风景'},
    {'name': '湘味楼', 'location': [28.1803, 112.9344], 'type': 'food', 'description': '在岳麓山附近餐厅用餐，可点不辣或微辣菜品'},
    {'name': '橘子洲', 'location': [28.1927, 112.9664], 'type': 'attraction', 'description': '参观毛泽东青年艺术雕塑，登问天台远眺长沙全景，欣赏"中国第一洲"的自然风光'},
    {'name': '文和友老长沙龙虾馆', 'location': [28.2062, 112.9783], 'type': 'food', 'description': '体验80年代怀旧老长沙的氛围，品尝口味虾（可要求微辣版本）'},
    {'name': '茶颜悦色', 'location': [28.2062, 112.9783], 'type': 'food', 'description': '品尝网红茶饮，休闲放松'}
]

# 第三天景点和美食
day3_locations = [
    {'name': '培元桥附近酒店', 'location': [28.1962, 112.9783], 'type': 'hotel', 'description': '酒店早餐'},
    {'name': '湖南省博物馆', 'location': [28.2119, 112.9783], 'type': 'attraction', 'description': '欣赏长沙马王堆汉墓陈列，了解湖南历史文化，参观特别展览'},
    {'name': '梅溪湖国际文化艺术中心', 'location': [28.2119, 112.8983], 'type': 'attraction', 'description': '欣赏扎哈·哈迪德设计的建筑，拍摄网红打卡照'},
    {'name': '梅溪湖中国结桥', 'location': [28.2119, 112.8983], 'type': 'attraction', 'description': '欣赏被CNN评为"世界最性感建筑"之一的桥梁，在湖边散步，享受悠闲时光'},
    {'name': '火宫殿', 'location': [28.1881, 112.9775], 'type': 'food', 'description': '品尝长沙著名老字号美食，尝试臭豆腐、姊妹团子等特色小吃'},
    {'name': '坡子街夜市', 'location': [28.1881, 112.9775], 'type': 'food', 'description': '体验长沙夜生活，品尝各种小吃，购买特色伴手礼'}
]

# 第四天景点和美食
day4_locations = [
    {'name': '培元桥附近酒店', 'location': [28.1962, 112.9783], 'type': 'hotel', 'description': '酒店早餐'},
    {'name': '谢子龙艺术馆', 'location': [28.2062, 112.9583], 'type': 'attraction', 'description': '欣赏影像艺术作品，体验文艺氛围'},
    {'name': '李自健美术馆', 'location': [28.2062, 112.9483], 'type': 'attraction', 'description': '欣赏"全球最大的艺术家个人美术馆"，了解现代艺术'},
    {'name': '长沙世界之窗', 'location': [28.2262, 112.9383], 'type': 'attraction', 'description': '欣赏世界各国建筑奇观，观看五洲风情歌舞表演，体验游乐设施'},
    {'name': '长沙站', 'location': [28.1917, 113.0119], 'type': 'transport', 'description': '从长沙站乘车返程'}
]

# 创建自定义HTML模板，使用本地CDN和高德地图
template = """
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>长沙旅游攻略地图</title>
    <script src="https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/leaflet/1.7.1/leaflet.min.js"></script>
    <script src="https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/leaflet.markercluster/1.5.0/leaflet.markercluster.js"></script>
    <link rel="stylesheet" href="https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/leaflet/1.7.1/leaflet.min.css"/>
    <link rel="stylesheet" href="https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/leaflet.markercluster/1.5.0/MarkerCluster.css"/>
    <link rel="stylesheet" href="https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/leaflet.markercluster/1.5.0/MarkerCluster.Default.css"/>
    <link rel="stylesheet" href="https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/font-awesome/5.15.4/css/all.min.css"/>
    <style>
        body {{
            margin: 0;
            padding: 0;
            font-family: Arial, sans-serif;
        }}
        #map {{
            width: 100%;
            height: 100vh;
        }}
        .legend {{
            position: fixed;
            bottom: 50px;
            left: 50px;
            width: 180px;
            height: 200px;
            border: 2px solid grey;
            z-index: 9999;
            font-size: 14px;
            background-color: white;
            padding: 10px;
            border-radius: 5px;
        }}
        .title {{
            position: fixed;
            top: 10px;
            left: 50%;
            transform: translateX(-50%);
            z-index: 9999;
            font-size: 18px;
            font-weight: bold;
            background-color: white;
            padding: 10px;
            border-radius: 5px;
            border: 2px solid grey;
        }}
        .custom-icon {{
            background: none;
            border: none;
        }}
        .custom-icon i {{
            font-size: 24px;
            text-shadow: 1px 1px 3px rgba(0,0,0,0.5);
        }}
    </style>
</head>
<body>
    <div id="map"></div>
    <div class="legend">
        <p><b>图例</b></p>
        <p><span style="color:red">●</span> 第1天</p>
        <p><span style="color:blue">●</span> 第2天</p>
        <p><span style="color:green">●</span> 第3天</p>
        <p><span style="color:purple">●</span> 第4天</p>
        <p><i class="fa fa-camera"></i> 景点</p>
        <p><i class="fa fa-utensils"></i> 美食</p>
        <p><i class="fa fa-shopping-cart"></i> 购物</p>
        <p><i class="fa fa-home"></i> 住宿</p>
        <p><i class="fa fa-subway"></i> 交通</p>
    </div>
    <div class="title">
        {title}
    </div>
    
    <script>
        // 初始化地图
        var map = L.map('map').setView([{center_lat}, {center_lng}], {zoom});
        
        // 添加高德地图底图
        L.tileLayer('https://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={{{{x}}}}&y={{{{y}}}}&z={{{{z}}}}', {{
            attribution: '&copy; 高德地图',
            maxZoom: 18
        }}).addTo(map);
        
        // 创建标记聚类
        var markers = L.markerClusterGroup();
        
        // 添加标记
        {markers_js}
        
        // 添加到地图
        map.addLayer(markers);
        
        // 添加路线
        {polyline_js}
    </script>
</body>
</html>
"""

# 创建每日行程地图 - 使用自定义模板和高德地图
def create_daily_map(day_number, locations, filename, title):
    # 准备标记JS代码
    markers_js = []
    locations_coords = []
    
    for i, loc in enumerate(locations):
        locations_coords.append(loc['location'])
        
        # 创建弹出窗口内容
        popup_content = f"""
        <b>{loc['name']}</b><br>
        {loc['description']}
        """
        
        # 准备图标代码
        icon_code = f"L.divIcon({{html: '<i class=\"fa fa-{icon_dict[loc['type']]}\" style=\"color:{colors[loc['type']]}\"></i>', className: 'custom-icon'}})"
        
        # 添加标记JS代码
        marker_js = f"""
        var marker{i} = L.marker([{loc['location'][0]}, {loc['location'][1]}], {{
            icon: {icon_code}
        }}).bindPopup("{popup_content}").bindTooltip("{i+1}. {loc['name']}");
        markers.addLayer(marker{i});
        """
        
        markers_js.append(marker_js)
    
    # 准备路线JS代码
    if len(locations_coords) > 1:
        coords_str = ", ".join([f"[{loc[0]}, {loc[1]}]" for loc in locations_coords])
        polyline_js = f"""
        var polyline = L.polyline([{coords_str}], {{
            color: 'blue',
            weight: 2.5,
            opacity: 0.8
        }}).addTo(map);
        """
    else:
        polyline_js = ""
    
    # 填充模板
    html_content = template.format(
        title=title,
        center_lat=changsha_center[0],
        center_lng=changsha_center[1],
        zoom=13,
        markers_js="\n".join(markers_js),
        polyline_js=polyline_js
    )
    
    # 保存地图
    with codecs.open(filename, 'w', 'utf-8') as f:
        f.write(html_content)

# 创建总览地图 - 使用自定义模板和高德地图
def create_overview_map(filename):
    # 准备标记JS代码
    markers_js = []
    
    # 定义每天的颜色
    day_colors = {1: 'red', 2: 'blue', 3: 'green', 4: 'purple'}
    
    # 添加所有地点标记
    all_locations = []
    for day, locations in enumerate([day1_locations, day2_locations, day3_locations, day4_locations], 1):
        for loc in locations:
            # 避免重复添加相同地点
            if loc['name'] not in [l.get('name') for l in all_locations]:
                loc['day'] = day
                all_locations.append(loc)
    
    # 添加标记
    for i, loc in enumerate(all_locations):
        # 创建弹出窗口内容
        popup_content = f"""
        <b>{loc['name']}</b><br>
        第{loc['day']}天<br>
        {loc['description']}
        """
        
        # 准备图标代码
        icon_code = f"L.divIcon({{html: '<i class=\"fa fa-{icon_dict[loc['type']]}\" style=\"color:{day_colors[loc['day']]}\"></i>', className: 'custom-icon'}})"
        
        # 添加标记JS代码
        marker_js = f"""
        var marker{i} = L.marker([{loc['location'][0]}, {loc['location'][1]}], {{
            icon: {icon_code}
        }}).bindPopup("{popup_content}").bindTooltip("{loc['name']} (第{loc['day']}天)");
        markers.addLayer(marker{i});
        """
        
        markers_js.append(marker_js)
    
    # 填充模板
    html_content = template.format(
        title="长沙四天三晚旅游攻略总览",
        center_lat=changsha_center[0],
        center_lng=changsha_center[1],
        zoom=12,
        markers_js="\n".join(markers_js),
        polyline_js=""
    )
    
    # 保存地图
    with codecs.open(filename, 'w', 'utf-8') as f:
        f.write(html_content)

# 创建四天的行程地图
create_daily_map(1, day1_locations, '/home/ubuntu/changsha-travel-guide/public/maps/day1_map.html', "长沙旅游攻略 - 第1天行程")
create_daily_map(2, day2_locations, '/home/ubuntu/changsha-travel-guide/public/maps/day2_map.html', "长沙旅游攻略 - 第2天行程")
create_daily_map(3, day3_locations, '/home/ubuntu/changsha-travel-guide/public/maps/day3_map.html', "长沙旅游攻略 - 第3天行程")
create_daily_map(4, day4_locations, '/home/ubuntu/changsha-travel-guide/public/maps/day4_map.html', "长沙旅游攻略 - 第4天行程")

# 创建总览地图
create_overview_map('/home/ubuntu/changsha-travel-guide/public/maps/overview_map.html')

print("所有地图已成功创建，使用高德地图底图和国内CDN，并修复了中文编码问题！")
